<template>
  <el-form ref="ruleFormRef" :model="form" :rules="rules" label-width="140">
    <el-form-item label="应用名称：" name="appName" prop="appName">
      <el-input v-model="form.appName" autocomplete="off" />
    </el-form-item>

    <el-form-item label="应用包名：" name="packageName" prop="packageName">
      <el-input v-model="form.packageName" autocomplete="off" />
    </el-form-item>

    <el-form-item label="应用发布平台：" name="plats" prop="plats">
      <el-checkbox-group v-model="form.plats">
        <el-checkbox v-for="plat in plats" :key="plat" :label="plat">{{ plat }}</el-checkbox>
      </el-checkbox-group>
    </el-form-item>

    <el-form-item style="display: flex; justify-content: flex-end">
      <el-button type="primary" @click="submitForm(ruleFormRef)">创建</el-button>
      <el-button @click="close">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { reactive, ref, inject } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { AddAppApi } from '../api'

const plats = ['oppo', 'xiaomi', 'huawei', 'vivo']

// 调用父级的关闭方法
const close: Function = inject('closeAppAdd') as Function
const refreshList: Function | undefined = inject('refreshList')

interface Form {
  appName: string
  packageName: string
  plats: string[]
}

const ruleFormRef = ref<FormInstance>()
const form = reactive<Form>({
  appName: '',
  packageName: '',
  plats: []
})

// 校验规则
const rules = reactive<FormRules<Form>>({
  appName: [{ required: true, message: '应用名称不能为空', trigger: 'blur' }],
  packageName: [{ required: true, message: '应用包名不能为空', trigger: 'blur' }],
  plats: [{ required: true, message: '应用发布平台不能为空', trigger: 'blur' }]
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      AddAppApi(form.appName, form.packageName, form.plats)
        .then((response) => {
          const data = response.data
          // 提交成功后关闭刷新页面
          if (data.code == 200) {
            if (refreshList) {
              refreshList()
            }
            ElMessage.success(data.msg)
            if (close) {
              close()
            }
          } else {
            ElMessage.error(data.msg)
          }
        })
        .catch((error) => {
          console.error(error)
        })
    } else {
      console.log('error submit!', fields)
    }
  })
}
</script>
